package com.am.mosl.cityandroid.mainboard;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.am.mosl.cityandroid.R;
import com.am.mosl.cityandroid.bean.ArticleColumn;
import com.am.mosl.cityandroid.bean.Column;
import com.am.mosl.cityandroid.bean.HeadArticle;
import com.am.mosl.cityandroid.constant.HttpConstant;
import com.am.mosl.cityandroid.util.DatabaseHelper;
import com.am.mosl.cityandroid.widget.SharePopWindow;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;

@SuppressLint("ValidFragment")
public class FragmentMain extends Fragment{

    public static final String TAG="FragmentMain";

    private PullToRefreshListView mActivityListView;
    private ListViewAdapter mArticleListAdapter=null;
    private FinalBitmap mFinalBitamp;
    private List<MainBoardentity> mainBoardentityList=new ArrayList<MainBoardentity>();

    private String mColumnId =null;
    private String mCityId=null;
    private View mNoArticle;
    private View mHasArticle;
    private boolean mHasData=false;

    static FinalHttp finalHttp=new FinalHttp();
    private int mLastItemId = -1;

    private Activity activity;

    private Handler myHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {

            super.handleMessage(msg);

            switch (msg.what){
                case 1:
                    if(mActivityListView.isRefreshing()){
                        mActivityListView.onRefreshComplete();
                        mArticleListAdapter.notifyDataSetChanged();
                    }

            }

        }
    };


    public FragmentMain(){

    }

    @SuppressLint("ValidFragment")
    public FragmentMain(String cityId,String mColumnId) {
        this.mColumnId = mColumnId;
        this.mCityId=cityId;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        this.activity=this.getActivity();
        mFinalBitamp = FinalBitmap.create(getActivity());//初始化FinalBitmap模块
        if(mColumnId !=null){
            GetHeadArticle(mCityId, mColumnId);
        }
    }
    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG,"onStart");
    }

    private void initViews(View v) {
            mNoArticle=(View)v.findViewById(R.id.fragment_text);
            mHasArticle=(View)v.findViewById(R.id.fragment_list);
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main,container,false);
        initRefreshListView(view);
        initViews(view);
        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG,"onPause");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG,"onResume");
    }

    private void initRefreshListView(View view) {

        mActivityListView=(PullToRefreshListView)view.findViewById(R.id.activity_list_view);
        mArticleListAdapter=new ListViewAdapter(getActivity(),mainBoardentityList);
        ListView actualListView = mActivityListView.getRefreshableView();
        actualListView.setAdapter(mArticleListAdapter);
        mActivityListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {

                if (PullToRefreshBase.Mode.PULL_FROM_START == refreshView.getCurrentMode()) {//上滑
                    mainBoardentityList.clear();
                    mArticleListAdapter.notifyDataSetChanged();
                    GetHeadArticle(mCityId, mColumnId);
                    mActivityListView.setClickable(false);
                } else if (PullToRefreshBase.Mode.PULL_FROM_END == refreshView.getCurrentMode()) { //下拉
                    GetArticleList(mCityId, mColumnId, mLastItemId + "", "5");
                    mActivityListView.setClickable(false);
                }
            }
        });
        mActivityListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

                if(scrollState==SCROLL_STATE_IDLE){

                    if(view.getLastVisiblePosition()==(view.getCount()-1)){
                        GetArticleList(mCityId, mColumnId, mLastItemId + "", "5");
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        mActivityListView.setMode(PullToRefreshBase.Mode.BOTH);

        mActivityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(FragmentMain.this.getActivity(), ActivityDetailActivity.class);
                ActivityDetailActivity.ShareData data = new ActivityDetailActivity.ShareData();
                TextView Textid = (TextView) view.findViewById(R.id.article_id);
                TextView titleText = (TextView) view.findViewById(R.id.activity_title);
                if(null!=titleText){
                	//if()
                	DatabaseHelper.getDatabaseHelper(activity).insert(Textid.getText().toString(), titleText.getText().toString()+"", "");
                	titleText.setTextColor(Color.GRAY);
                }
                MainBoardentity boardentity=(MainBoardentity)mArticleListAdapter.getItem((int)id);
                if(boardentity.type==MainBoardentity.TYPE_HEAD){

                    HeadArticle headArticle=boardentity.headArticle;
                    data.des=headArticle.getTitle();
                    data.title="百城通";
                    data.imageUrl =headArticle.getImage();

                }else{

                    ArticleColumn articleColumn=boardentity.articleColumn;
                    data.title=articleColumn.getTitle();
                    data.imageUrl=articleColumn.getImage();
                    data.des=articleColumn.getIntroduction();

                }
                    intent.putExtra(ActivityDetailActivity.Intent_To_ArticleDetail, Textid.getText());
                     Bundle bundle = new Bundle();
                     bundle.putSerializable("data",data);
                    intent.putExtras(bundle);
                    intent.putExtra("cityId",mCityId);
                    startActivity(intent);
            }
        });
    }

    class ListViewAdapter extends BaseAdapter {

        private Context context;
        private List<MainBoardentity> list;
        public ListViewAdapter(Context context,List<MainBoardentity> list){
            this.context=context;
            this.list=list;
        }

        @Override
        public int getCount() {
            return list.size();
        }
        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            MainBoardentity boardentity=list.get(position);

            if(boardentity.type==MainBoardentity.TYPE_HEAD){  //置顶文章
                HeadArticle headArticle=boardentity.headArticle;
                convertView=LayoutInflater.from(context).inflate(R.layout.main_activity_list_view_1,parent,false);
                ImageView head=(ImageView)convertView.findViewById(R.id.main_activity_list_image);
                TextView url_image=(TextView)convertView.findViewById(R.id.url_image);
                url_image.setText(headArticle.getImage());
                mFinalBitamp.display(head,headArticle.getImage());
                TextView title=(TextView)convertView.findViewById(R.id.title);
                TextView textId=(TextView)convertView.findViewById(R.id.article_id);
                textId.setText(Integer.toString(headArticle.getId()));
                title.setText(headArticle.getTitle());
            }else{

                ArticleColumn articleColumn=boardentity.articleColumn;
                convertView=LayoutInflater.from(context).inflate(R.layout.main_activity_list_view_2,parent,false);
                TextView id=(TextView)convertView.findViewById(R.id.article_id);
                id.setText(articleColumn.getId()+"");
                ImageView imageView=(ImageView)convertView.findViewById(R.id.activity_image);
                TextView url_image=(TextView)convertView.findViewById(R.id.url_image);
                url_image.setText(articleColumn.getImage());
                mFinalBitamp.display(imageView,articleColumn.getImage());
                TextView textView=(TextView)convertView.findViewById(R.id.activity_title);
                if(null!=textView){
                	Cursor cu = DatabaseHelper.getDatabaseHelper(activity).query("id=?",new String[]{articleColumn.getId()+""});
                	if(cu.getCount()>0){
                		textView.setTextColor(Color.GRAY);
                	}
                }
                textView.setText(articleColumn.getTitle());
                TextView introduction=(TextView)convertView.findViewById(R.id.introduction);
                introduction.setText(articleColumn.getIntroduction());

            }

           return convertView;
        }

   }
    //获得文章列表
    public final void GetArticleList(String cityId,String columnId,String contentId,String count){

        AjaxParams params=new AjaxParams();
        params.put("cityid",cityId);
        params.put("columnid",columnId);
        params.put("contentid",contentId);
        params.put("count",count);

        finalHttp.post(HttpConstant.ArticleList,params,new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);

                try {
                    JSONObject jsonObject=new JSONObject(o.toString());
                    Log.d("momo",jsonObject.toString());
                    String status=(String)jsonObject.opt("status");
                    if(status.endsWith("1")){ //获取成功

                        JSONArray jsonArray=(JSONArray)jsonObject.opt("data");
                        Log.d(TAG, jsonArray.toString());
                        List<ArticleColumn> articleColumnList= JSON.parseArray(jsonArray.toString(), ArticleColumn.class);
                        for(int i=0;i<articleColumnList.size();i++){
                            MainBoardentity boardentity=new MainBoardentity();
                            boardentity.type=MainBoardentity.TYPE_ARTICE;
                            boardentity.articleColumn=articleColumnList.get(i);
                            mainBoardentityList.add(boardentity);
                        }

                        mLastItemId = articleColumnList.get(articleColumnList.size()-1).getId()-1;
                        mArticleListAdapter.notifyDataSetChanged();
                        myHandler.sendEmptyMessage(1);
                    }
                    if(status.endsWith("0")){
                        myHandler.sendEmptyMessage(1);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                myHandler.sendEmptyMessage(1);
            }
        });
    }

    //获得置顶文章
    public  final void GetHeadArticle(String cityId,String columnId){

        AjaxParams ajaxParams=new AjaxParams();
        ajaxParams.put("cityid",cityId);
        ajaxParams.put("columnid",columnId);
        finalHttp.post(HttpConstant.HeadArticle,ajaxParams,new AjaxCallBack<Object>() {

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                Log.d(TAG, o.toString());
                GetArticleList(mCityId, mColumnId,"-1","5");  //开始获取文章列表
                try {
                    JSONObject jsonObject=new JSONObject(o.toString());
                    String status =(String) jsonObject.opt("status");
                    if(status.endsWith("1")){
                        JSONObject object=(JSONObject)jsonObject.opt("data");
                        HeadArticle headArticle=JSON.parseObject(object.toString(),HeadArticle.class);

                        MainBoardentity boardentity=new MainBoardentity();
                        boardentity.type=MainBoardentity.TYPE_HEAD;
                        boardentity.headArticle=headArticle;
                        mainBoardentityList.add(boardentity);
                        mArticleListAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

}
